import ValuePair from "./ValuePair";
import {loseloseHashCode, defaultToString} from "./loseloseHashCode";
import isEmpty from "../utils/isEmpty";
// 散列表简单实现
// 这里使用lose lose散列算法
// 所谓的lose散列算法就是获取key的ASCII码然后加起来, 之后除以一个值的余数

export interface HashDictionaryInterface<TK, TV> {
  toStrFn: (item: any) => string;
  loseloseHashCode: loseloseHashCode;
  item: { [index: number]: ValuePair<TK, TV> };
  put: (key: TK, value: TV) => void;
  get: (key: TK) => ValuePair<TK, TV> | undefined;
  remove: (key: TK) => ValuePair<TK, TV> | undefined;
}

/**
 * 最简单的实现, 不考虑HashCode重复
 */
export default class HashDictionary<TK, TV> implements HashDictionaryInterface<TK, TV> {
  toStrFn: (item: any) => string;
  item: { [index: number]: ValuePair<TK, TV> };
  loseloseHashCode: loseloseHashCode;

  constructor(toStrFn: (item: any) => string = defaultToString, max: number = 36) {
    this.toStrFn = toStrFn;
    this.item = {};
    this.loseloseHashCode = new loseloseHashCode(toStrFn, max);
  }

  put(key: TK, value: TV): void {
    let el = this.get(key);
    if (isEmpty(el)) {
      this.item[this.loseloseHashCode.getCode(key)] = new ValuePair(key, value);
    }else {
      (el as ValuePair<TK, TV>).value = value;
    }
  }

  get(key: TK): ValuePair<TK, TV> | undefined {
    return this.item[this.loseloseHashCode.getCode(key)]
  }

  remove(key: TK): ValuePair<TK, TV> | undefined {
    let el = this.get(key);
    delete this.item[this.loseloseHashCode.getCode(key)]
    return el;
  }


}

let hashMap = new HashDictionary<string,number>()
function print(){
  console.log("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-")
  console.log("java",hashMap.get("java"));
  console.log("javaScript",hashMap.get("javaScript"));
}
print();
hashMap.put("javaScript",0);
print();

hashMap.put("java",1);
print();

hashMap.put("javaScript",2);
print();

hashMap.remove("java")
print();
